#!/usr/bin/python
#coding: utf-8

import sys
sys.path.append("..")

from Logging.UrlLogging import log_Main
from Config.Config import conn, CreatePageUrl, Select_Sql_Page_Url2, PROCEDURE1

class AllPageMySql(object):
    def __init__(self):
        self.conn = conn
        self.createPageUrl = CreatePageUrl
        self.cur = self.conn.cursor()
        self.insert_sql = "insert into pageurl(url, name) values('%s', '%s');"

    def Create(self):
        # log_Main(u"创建数据库以及数据表", "info")
        try:
            self.cur.execute("create database if not exists appchina;")
            self.conn.select_db("appchina")
            self.cur.execute(self.createPageUrl)

            self.conn.commit()
        except Exception as e:
            self.conn.rollback()
        else:
            # 每次在插入的时候都需要重新获取数据库中存储的语句，因为数据库一直在更新的过程中
            self.cur.execute(Select_Sql_Page_Url2)
            self.pageurls = list(self.cur.fetchall())

        # 创建存储过程
        try:
            self.cur.execute(PROCEDURE1)

            self.conn.commit()
            print u"创建存储过程成功！！！！"
        except Exception as e:
            self.conn.rollback()

    def Insert(self, urls):
        for url in urls:
            print url
            if url in self.pageurls:
                print u"数据表page_url中已经存在该条数据"
                continue
            try:
                # 使用insert进行存储
                # self.cur.execute(self.insert_sql % url)
                # 使用存储过程进行存储
                self.cur.execute("call p1('%s', '%s');" % url)
                # log_Main(u"存入数据库成功", "info")
                self.conn.commit()
            except Exception as e:
                print e
                # log_Main(e, "error")
                self.conn.rollback()

    def Close(self):
        # log_Main(u"每次执行完以后都进行关闭操作", "info")
        self.cur.close()
        self.conn.close()

if __name__ == "__main__":
    a = AllPageMySql()
    a.Create()